﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
using WIA;
using System.Runtime.InteropServices;


namespace ScanBook
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //
        string wiaDeviceID = "";
        WIA.Device wiaDevice = null;
        //
        int imageNumber = 0;
        //
        bool is600dpi = false;
        bool isHalfPage = false;
        //
        public MainWindow()
        {
            InitializeComponent();
            //
            try
            {
                if ("" == Properties.Settings.Default.DestinationDirectory)
                {
                    Properties.Settings.Default.DestinationDirectory = @"D:\Share\Scanner";
                    Properties.Settings.Default.Save();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Properties Error)");
                Environment.Exit(1);
            }
            try
            {
                WiaWrapper.SetDestiantionDirectory(Properties.Settings.Default.DestinationDirectory);
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message, "WIA Error)");
                Environment.Exit(1);
            }
            //WiaWrapper.SetImageFileNamePattern("img{0:000}.jpg");
            //uc_PageChangeReminder.ocp = new UC_PageChangeReminder.OnChangePage(OnChangePageEvent);
            //
        }

        private void button_Do_Click(object sender, RoutedEventArgs e)
        {
            //http://forums.codeguru.com/showthread.php?439027-Windows-Image-Acquisition-(WIA)-Code
            //http://www.nakov.com/blog/2009/11/17/playing-with-the-scanner-with-wia-and-c/
            button_Do.IsEnabled = false;
            checkBox.IsEnabled = false;
            //
            if ("" == wiaDeviceID)
            {
                wiaDeviceID = WiaWrapper.SelectScanner();
                wiaDevice = WiaWrapper.ConnectScanner(wiaDeviceID);
                //
                imageNumber = WiaWrapper.GetLastPageNumber();
            }


            //WiaWrapper.GetScanners();

            if ("" == wiaDeviceID)
            {
                System.Windows.MessageBox.Show("Scanner not connected", "DeviceID", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                button_Do.IsEnabled = true;
                checkBox.IsEnabled = true;
                return;
            }

            //=====================================================================

            window1.Title = "";
            taskbar1.ProgressValue = 0.0;
            showPage0();
            //
            try
            {
                WIA.CommonDialog wiaDialog = new WIA.CommonDialog();
                WIA.Item wiaItem = wiaDevice.Items[1] as WIA.Item;
                WiaWrapper.GetAvailableDPI(wiaItem);

                if (null == wiaDevice)
                {
                    System.Windows.MessageBox.Show("null == wiaDevice", "wiaDevice", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                    return;
                }
                //
                //
                imageNumber++;
                button_Do.Content = (imageNumber+1).ToString();
                //
                if (1 == countPageSide())
                {
                    textBox.Text = string.Format("2 / 2");
                    window1.Title = "★";
                    taskbar1.ProgressValue = 1.0;
                }
                else
                {
                    textBox.Text = string.Format("1 / 2");
                    window1.Title = "";
                    taskbar1.ProgressValue = 0.5;
                }
                //
                //
                //uc_PageChangeReminder.SetPageNumber(imageNumber);
                string pathName = WiaWrapper.GetImageFilePathName(imageNumber);
                //
                WiaWrapper.SetParameters(wiaItem, isHalfPage, is600dpi ? 600 : 300);
                //
                //
                WiaWrapper.ScanAndSave(wiaDialog, wiaItem, pathName);// <<== SCANNING
                //
                if (1 == countPageSide())
                {
                    showPage1();
                }
                //
                //
                window1.Topmost = true;
                window1.Refresh();
                window1.Topmost = false;
            }
            catch (Exception e1)
            {
                System.Windows.MessageBox.Show(e1.Message, e1.Source, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                button_Do.IsEnabled = true;
                checkBox.IsEnabled = true; ;
            }
            //
            return;
        }
#if false
            WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();

            bool hasMorePages = true;
            int x = 0;
            int numPages = 0;


            while (hasMorePages)
            {
                //Create DeviceManager
                DeviceManager manager = new DeviceManager();
                Device WiaDev = null;
                foreach (DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == DeviceID)
                    {
                        WIA.Properties infoprop = null;
                        infoprop = info.Properties;

                        //connect to scanner
                        WiaDev = info.Connect();
                        

                        break;
                    }
                }



                //Start Scan

                WIA.ImageFile img = null;
                WIA.Item Item = WiaDev.Items[1] as WIA.Item;
                try
                {

                    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, wiaFormatJPEG, false);


                    //process image:
                    //one would do image processing here
                    //

                    //Save to file
                    string varImageFileName = "c:\\test" + x.ToString() + ".jpg";
                    if (File.Exists(varImageFileName))
                    {
                        //file exists, delete it
                        File.Delete(varImageFileName);
                    }
                    img.SaveFile(varImageFileName);
                    numPages++;
                    img = null;

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
                finally
                {
                    Item = null;
                    //determine if there are any more pages waiting
                    Property documentHandlingSelect = null;
                    Property documentHandlingStatus = null;
                    foreach (Property prop in WiaDev.Properties)
                    {
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
                            documentHandlingSelect = prop;
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
                            documentHandlingStatus = prop;


                    }

                    hasMorePages = false; //assume there are no more pages
                    if (documentHandlingSelect != null)
                    //may not exist on flatbed scanner but required for feeder
                    {
                        //check for document feeder
                        if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
                        {
                            hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
                        }
                    }
                    x++;
                }
            }
			
		
#endif

        private void HalfPage_Checked_1(object sender, RoutedEventArgs e)
        {
            isHalfPage = true;
        }
        private void HalfPage_Unchecked_1(object sender, RoutedEventArgs e)
        {
            isHalfPage = false;
        }

        private void dpi600_Checked_1(object sender, RoutedEventArgs e)
        {
            is600dpi = false;
        }
        private void dpi600_Unchecked_1(object sender, RoutedEventArgs e)
        {
            is600dpi = false;
        }
        private void Destination_Directory_1(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
            fbd.SelectedPath = Properties.Settings.Default.DestinationDirectory;
            if (System.Windows.Forms.DialogResult.OK == fbd.ShowDialog())
            {
                Properties.Settings.Default.DestinationDirectory = fbd.SelectedPath;
                Properties.Settings.Default.Save();
                WiaWrapper.SetDestiantionDirectory(Properties.Settings.Default.DestinationDirectory);
            }
        }

        private void checkBox_Checked(object sender, RoutedEventArgs e)
        {
        }

        private void checkBox_Unchecked(object sender, RoutedEventArgs e)
        {
        }

        private int countPageSide()
        {
            return (0 == ((imageNumber + (((bool)checkBox.IsChecked)?1:0)) % 2)) ? 0 : 1;
        }

        private void showPage0()
        {
            textBox.Background = Brushes.LightGreen;
            textBox.Refresh();
            System.Threading.Thread.Sleep(100);
        }

        private void showPage1()
        {
            textBox.Background = Brushes.Coral;
            textBox.Refresh();
            System.Threading.Thread.Sleep(100);
        }

    }//class







        
            


           

            /*
            wiaImage = wiaDiag.ShowAcquireImage(
            WiaDeviceType.UnspecifiedDeviceType, 
            WiaImageIntent.GrayscaleIntent, 
            WiaImageBias.MaximizeQuality, 
            wiaFormatJPEG, true, true, false);


            //Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));
            //i.Save(filename);
            WIA.Vector vector = wiaImage.FileData;
             */
    class WIA_DPS_DOCUMENT_HANDLING_SELECT
	{
		public const uint FEEDER = 0x00000001;
		public const uint FLATBED = 0x00000002;
	}

	class WIA_DPS_DOCUMENT_HANDLING_STATUS
	{
		public const uint FEED_READY = 0x00000001;
	}

	class WIA_PROPERTIES
	{
		public const uint WIA_RESERVED_FOR_NEW_PROPS = 1024;
		public const uint WIA_DIP_FIRST = 2;
		public const uint WIA_DPA_FIRST  =  WIA_DIP_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
		public const uint WIA_DPC_FIRST  = WIA_DPA_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
		//
		// Scanner only device properties (DPS)
		//
		public const uint WIA_DPS_FIRST    =                      WIA_DPC_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
		public const uint WIA_DPS_DOCUMENT_HANDLING_STATUS  =     WIA_DPS_FIRST + 13;
		public const uint WIA_DPS_DOCUMENT_HANDLING_SELECT  =     WIA_DPS_FIRST + 14;
	}

    class WIA_ERRORS
    {
        public const uint BASE_VAL_WIA_ERROR = 0x80210000;
        public const uint WIA_ERROR_PAPER_EMPTY = BASE_VAL_WIA_ERROR + 3;
    }



    public static class ExtensionMethods
    {
        private static Action EmptyDelegate = delegate() { };
        public static void Refresh(this UIElement uiElement)
        {
            uiElement.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, EmptyDelegate);
        }
    }


}
